package com.icoolkj.ms.common.core.handler;

import cn.hutool.core.util.CharsetUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.icoolkj.ms.common.core.exception.IcoolkjMSException;
import com.icoolkj.ms.common.core.response.ServerResponseEntity;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author icoolkj
 * @version 1.0
 * @description
 * @createDate 2025/02/10 19:28
 */
@Slf4j
@Component
public class HttpHandler {

    @Autowired
    private ObjectMapper objectMapper;

    public <T> void printServerResponseToWeb(ServerResponseEntity<T> serverResponseEntity) {
        if (serverResponseEntity == null) {
            log.info("print obj is null");
            return;
        }

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            log.error("requestAttributes is null, can not print to web");
            return;
        }
        HttpServletResponse response = requestAttributes.getResponse();
        if (response == null) {
            log.error("httpServletResponse is null, can not print to web");
            return;
        }

        // 根据响应状态记录不同级别的日志
        if (!serverResponseEntity.isSuccess()) {
            log.error("response error: {}", serverResponseEntity.getMessage());
        } else {
            log.info("response success: {}", serverResponseEntity.getMessage());
        }
        response.setCharacterEncoding(CharsetUtil.UTF_8);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);

        try (PrintWriter printWriter = response.getWriter()){
            printWriter.write(objectMapper.writeValueAsString(serverResponseEntity));
            printWriter.flush();
        }
        catch (IOException e) {
            String errorMessage = "Failed to write response to web. ServerResponseEntity: " + serverResponseEntity;
            log.error(errorMessage, e);
            throw new IcoolkjMSException(errorMessage, e);
        }
    }

}
